
package com.boyuan.huijiaoyu;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.tsz.afinal.core.AsyncTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.boyuan.huijiaoyu.R;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.StringUtils;
import com.ttcaca.cas.android.client.Main;
import com.ttcaca.cas.android.client.utils.Helper;

public class Html5_Activity extends BaseActivity implements OnClickListener {

	private final String TAG = "Html5_Activity";
	protected static final int FILECHOOSER_RESULTCODE = 0;
	private static final int FILE_SELECT_CODE = 4;

	private TextView txtTitle;
	private Button btnBack;
	private ImageButton imageBtnRefresh;
	private WebView webView;

	private String website;
	private String title;

	protected ValueCallback<Uri> mUploadMessage;
	private WebChromeClient wcc;
	private int isShowLoading = 0;// 1为商品列表 不需要loading 0位默认需要loading
	// 是否跳出应用去三方应用
		private boolean isJumpOutOfThirdApp = false;
	private TextView tv_father_level;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.html5_activity);

		Intent data = getIntent();
		if (data.getExtras() != null) {
			website = data.getExtras().getString("addr");
			title = data.getExtras().getString("title");
			isShowLoading = data.getExtras().getInt("isloading");
			father_level = data.getExtras().getString("father_level");
		}

		prepareView();

		synCookies(Html5_Activity.this, Main.CAS_DOMAIN);

		if (webView != null && StringUtils.isNotEmpty(website)) {
			Log.i(TAG, "website = " + website);
			webView.loadUrl(website);
		}
	}

	@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
	private void prepareView() {

		txtTitle = (TextView) findViewById(R.id.txt_title);
		txtTitle.setText(title);
		
		tv_father_level = (TextView) findViewById(R.id.tv_father_level);
		tv_father_level.setText(father_level);
		
		
		findViewById(R.id.lay_back1).setOnClickListener(this);
		
		imageBtnRefresh = (ImageButton) findViewById(R.id.imageBtnRefresh);
		imageBtnRefresh.setOnClickListener(this);

		webView = (WebView) findViewById(R.id.webview);
		webView.requestFocusFromTouch();

		// webView.loadUrl(website);

		webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.startsWith("tel:")) {
					isJumpOutOfThirdApp = true;
					Intent intent = new Intent(Intent.ACTION_DIAL, Uri
							.parse(url));
					startActivity(intent);
				} else {
					// 使用webview打开网页
					view.loadUrl(url);
				}
				return true;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {

				// 数据加载中……
				if (isShowLoading == 0) {
					isShowLoading = 1;
					showLoading(getResources().getString(R.string.loading_data));
				}

				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				hideLoading();
				super.onPageFinished(view, url);
			}
		});
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setAllowFileAccess(true);// 设置允许访问文件数据
		settings.setLoadsImagesAutomatically(true);
		settings.setUseWideViewPort(true);
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);
		settings.setLoadWithOverviewMode(true);

		// 开启js
		// webView.setWebChromeClient(new WebChromeClient() {
		//
		// @Override
		// public boolean onJsAlert(WebView view, String url, String message,
		// JsResult result) {
		//
		// return super.onJsAlert(view, url, message, result);
		// }
		//
		// });

		Helper.setContext(getApplicationContext());
		webView.addJavascriptInterface(new JSInvokeClass(), "myjava");
		webView.setDownloadListener(new MyWebViewDownLoadListener());

		wcc = new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				result.confirm();
				return true;
			}

			@Override
			public void onGeolocationPermissionsShowPrompt(String origin,
					GeolocationPermissions.Callback callback) {
				callback.invoke(origin, true, false);
				super.onGeolocationPermissionsShowPrompt(origin, callback);
			}

			// // js上传文件的<input type="file" name="fileField" id="fileField"
			// />事件捕获
			// // Android > 4.1.1 调用这个方法
			// public void openFileChooser(ValueCallback<Uri> uploadMsg,
			// String acceptType, String capture) {
			//
			// isBackIntoTheFrontDesk = true;
			// mUploadMessage = uploadMsg;
			// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			// intent.addCategory(Intent.CATEGORY_OPENABLE);
			// intent.setType("image/*");
			// startActivityForResult(
			// Intent.createChooser(intent, "完成操作需要使用"),
			// FILECHOOSER_RESULTCODE);
			//
			// }
			//
			// // 3.0 + 调用这个方法
			//
			// public void openFileChooser(ValueCallback<Uri> uploadMsg,
			// String acceptType) {
			// isBackIntoTheFrontDesk = true;
			// mUploadMessage = uploadMsg;
			// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			// intent.addCategory(Intent.CATEGORY_OPENABLE);
			// intent.setType("image/*");
			// startActivityForResult(
			// Intent.createChooser(intent, "完成操作需要使用"),
			// FILECHOOSER_RESULTCODE);
			// }
			//
			// // Android < 3.0 调用这个方法
			// public void openFileChooser(ValueCallback<Uri> uploadMsg) {
			// isBackIntoTheFrontDesk = true;
			// mUploadMessage = uploadMsg;
			// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			// intent.addCategory(Intent.CATEGORY_OPENABLE);
			// intent.setType("image/*");
			// startActivityForResult(
			// Intent.createChooser(intent, "完成操作需要使用"),
			// FILECHOOSER_RESULTCODE);
			//
			// }

		};

		webView.setWebChromeClient(wcc);
		Helper.setContext(getApplicationContext());
	}

	/**
	 * Context context, 同步一下cookie
	 */
	private void synCookies(Context context, String url) {
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
		// cookieManager.removeSessionCookie();// 移除
		// cookieManager.removeAllCookie();
		String cookies = SharePreferenceHelper
				.getStringValue(context, "COOKIE");

		cookieManager.setCookie(url, cookies);// cookies是在HttpClient中获得的cookie
		CookieSyncManager.getInstance().sync();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.lay_back1:
			onBackPressed();
			break;
		case R.id.imageBtnRefresh:

			webView.reload();

			break;
		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (isBackIntoTheFrontDesk) {
			isBackIntoTheFrontDesk = false;
		}
		
		if (isJumpOutOfThirdApp) {
			isJumpOutOfThirdApp = false;
			isBackIntoTheFrontDesk = false;
		}
		super.onResume();
	}

	/**
	 * 返回文件选择
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// if (requestCode == FILECHOOSER_RESULTCODE) {
		// if (null == mUploadMessage)
		// return;
		// Uri result = intent == null || resultCode != Activity.RESULT_OK ?
		// null
		// : intent.getData();
		//
		// mUploadMessage.onReceiveValue(result);
		// mUploadMessage = null;
		//
		// }

		// TODO
		if (resultCode == Activity.RESULT_OK && requestCode == FILE_SELECT_CODE) {
			// Get the Uri of the selected file
			Uri uri = intent.getData();
			String file = Helper.getFileAbsolutePath(Html5_Activity.this, uri);
			Helper.uploadFile(file, webView);
			Helper.showToast(getApplicationContext(), "后台上传中！");
		}
	}

	/** 网页Javascript调用接口 **/
	class JSInvokeClass {
		@JavascriptInterface
		public void uploadFile(String json) {
			Helper.setParams(json);
			showFileChooser();
		}

	}

	private void showFileChooser() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("*/*");
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		try {
			startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
					FILE_SELECT_CODE);
			isBackIntoTheFrontDesk = true;
		} catch (android.content.ActivityNotFoundException ex) {
			// Potentially direct the user to the Market with a Dialog
			Toast.makeText(Html5_Activity.this, "请安装文件管理器", Toast.LENGTH_SHORT)
					.show();
		}
	}

	private class MyWebViewDownLoadListener implements DownloadListener {

		@Override
		public void onDownloadStart(String url, String userAgent,
				String contentDisposition, String mimetype, long contentLength) {
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				Toast t = Toast.makeText(Html5_Activity.this, "需要SD卡。",
						Toast.LENGTH_LONG);
				t.setGravity(Gravity.CENTER, 0, 0);
				t.show();
				return;
			}
			Log.e("onDownloadStart", "contentDisposition:" + contentDisposition);
			DownloaderTask task;
			if (contentDisposition.contains("fileName=")) {
				String fileName = getName(contentDisposition);
				task = new DownloaderTask(fileName);
			} else {
				task = new DownloaderTask();
			}
			task.execute(url);
		}

		private String getName(String contentDisposition) {
			int lastIndexOf = contentDisposition.lastIndexOf("fileName=");
			return contentDisposition.substring(lastIndexOf + 9,
					contentDisposition.length());
		}

	}

	private class DownloaderTask extends AsyncTask<String, Void, String> {

		private String fileName;

		public DownloaderTask() {

		}

		public DownloaderTask(String fileName) {
			this.fileName = fileName;
		}

		@Override
		protected String doInBackground(String... params) {
			String url = params[0];
			if (fileName == null || fileName.equals("")) {
				fileName = Helper.getReallyFileName(url);
			}
			Log.e("tag", "fileName=" + fileName);
			File directory = Environment.getExternalStorageDirectory();
			File file = new File(directory, fileName);
			if (file.exists()) {
				Log.e("tag", "The file has already exists.");
				return fileName;
			}
			InputStream input = null;
			try {
				URL fileUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) fileUrl
						.openConnection();
				if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
					// 错误提示
					return null;
				}
				input = conn.getInputStream();

				Helper.writeToDownload(fileName, input);
				return fileName;

			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				if (input != null) {
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			closeProgressDialog();
			if (result == null) {
				Toast t = Toast.makeText(Html5_Activity.this, "连接错误！请稍后再试！",
						Toast.LENGTH_LONG);
				t.setGravity(Gravity.CENTER, 0, 0);
				t.show();
				return;
			}

			Toast t = Toast.makeText(Html5_Activity.this, "已保存到SD卡。",
					Toast.LENGTH_LONG);
			t.setGravity(Gravity.CENTER, 0, 0);
			t.show();

			// 下载完成后调用第三方打开
			// File directory = new
			// File(Environment.getExternalStorageDirectory()
			// + "/colourlife/download/");
			// // File directory = Environment.getExternalStorageDirectory();
			// File file = new File(directory, result);
			// Log.i("tag", "Path=" + file.getAbsolutePath());
			// Intent intent = getFileIntent(file);
			// startActivity(intent);

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showProgressDialog();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	private ProgressDialog mDialog;
	private String father_level;

	private void showProgressDialog() {
		if (mDialog == null) {
			mDialog = new ProgressDialog(Html5_Activity.this);
			mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
			mDialog.setMessage("正在加载 ，请等待...");
			mDialog.setIndeterminate(false);// 设置进度条是否为不明确
			mDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					mDialog = null;
				}
			});
			mDialog.show();

		}
	}

	private void closeProgressDialog() {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
	}

	@Override
	public void backClicked() {

		if (isShowingLoading()) {

			Log.e(TAG, "hideLoading");

			hideLoading();

		} else {
			isBackAllowed = true;
		}
	}
}
